package org.chickymate.server.controller.command.json;

import java.util.List;

import org.chickymate.server.controller.RequestWrapper;
import org.chickymate.server.model.Host;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GetMostCommentedHostCommand extends JSONAbstractCommand {

	@Override
	protected Object execute(RequestWrapper request) {
		return getCommentDao().getPopularHosts();
	}

	@Override
	protected JSONObject resultToJson(Object object) throws JSONException {
		return fromListToJsonObject((List<Host>)object);
	}
	
	private JSONObject fromListToJsonObject(List<Host> hosts) throws JSONException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", this.fromListToJSonArray(hosts));
		return jsonObject;
	}

	private JSONArray fromListToJSonArray(List<Host> hosts) throws JSONException {
		JSONArray jsonArray = new JSONArray();
		for (Host host : hosts) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("host", host.getHost());			
			jsonObject.put("positiveVotes", host.getPositiveVotes());
			jsonObject.put("negativeVotes", host.getNegativeVotes());
			jsonArray.put(jsonObject);
		}
		return jsonArray;
	}
	
}
